class WeixinUser < ActiveRecord::Base
	belongs_to :weixin_group

	validates_presence_of :openid

	scope :by_weixin_group_id, ->(weixin_group_id){where(weixin_group_id: weixin_group_id) if weixin_group_id.present?}

	cattr_accessor :fetch_thread  

	def self.fetch
		$fetch_thread = Thread.new{
			begin
				followers = $client.followers.result["data"]['openid']
				Thread.current[:followres_count] = followers.count
				Thread.current[:completed] = 0
			rescue
				raise "获取获取关注者列表失败" 
			end
			followers.each do |openid|
				inset_to(openid)
				Thread.current[:completed] += 1
			end
		}
	end

	def show_sex
		['未知', '男', '女'][self.sex.to_i]
	end

	def local_subscribe_time
		return if subscribe_time.blank?
		subscribe_time.localtime.strftime("%Y-%m-%d %H:%M:%S")
	end

	private
	def self.inset_to(openid)
		begin
			wx_id = $client.get_group_for(openid).result['groupid']
			weixin_group = WeixinGroup.find_by(wx_id: wx_id)
			user_info = $client.user(openid).result.merge(weixin_group_id: weixin_group.id)
			subscribe_time  = Time.at user_info.delete('subscribe_time')
			weixin_user = self.find_or_create_by(openid:  user_info.delete("openid"))
			weixin_user.update_columns(user_info.merge(subscribe_time: subscribe_time))
		rescue 
		end
	end
end
